/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.handler.netty;

import cn.hutool.json.JSONUtil;

import com.cetccloud.cimp.adapter.datasource.redis.impl.RedisServiceImpl;
import com.cetccloud.cimp.adapter.handler.abstracts.AbstractCheckHandler;
import com.cetccloud.cimp.common.util.SchemaValidatorUtil;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.nio.Buffer;

/**
 * @author
 * @apiNote 数据校验
 * @date 2023/1/6 11:01
 */
@Component("tcpCheckHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TcpCheckHandler extends AbstractCheckHandler {
    private final static InternalLogger logger = InternalLoggerFactory.getInstance(TcpCheckHandler.class);

    @Autowired
    RedisServiceImpl redisService;

    /**
     * 检查数据格式是否符合定义规范
     */
    @Override
    public boolean validate(Buffer buffer, Object context, String... paramPath) {       
    	String checkJsonStr = new String((byte[]) buffer.array());
        logger.info("需要校验检查的数据结果：{}", checkJsonStr);

        SchemaValidatorUtil.ValidState  validState =
                SchemaValidatorUtil.validSchema(checkJsonStr,
                        redisService.getCheckSchema((String) context));
        logger.info("数据校验结果::{}", JSONUtil.toJsonStr(validState));
        return validState.getSuccess();
    }
}
